{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "Chapter 07\n",
    "# 使用嵌套for循环计算矩阵乘法\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [],
   "source": [
    "# 定义矩阵 A 和 B\n",
    "A = [[1, 2, 10, 20],\n",
    "     [3, 4, 30, 40],\n",
    "     [5, 6, 50, 60]]\n",
    "\n",
    "B = [[4, 2],\n",
    "     [3, 1],\n",
    "     [40, 20],\n",
    "     [30, 10]]"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T10:44:21.582339Z",
     "end_time": "2024-07-03T10:44:21.591745Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "# 定义全 0 矩阵 C 用来存放结果\n",
    "C = [[0, 0],\n",
    "     [0, 0],\n",
    "     [0, 0]]"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T10:44:29.279892Z",
     "end_time": "2024-07-03T10:44:29.290523Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "# 矩阵乘法\n",
    "\n",
    "# 遍历 A 的行\n",
    "for i in range(len(A)):  # len(A) 给出 A 的行数\n",
    "    # 遍历 B 的列\n",
    "    for j in range(len(B[0])):\n",
    "        # len(B[0]) 给出 B 的列数\n",
    "        # 这一层相当于消去 k 所在的维度，即压缩\n",
    "        for k in range(len(B)):\n",
    "            C[i][j] += A[i][k] * B[k][j]\n",
    "            # 完成对应元素相乘，再求和"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T10:44:57.195334Z",
     "end_time": "2024-07-03T10:44:57.203455Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1010, 404]\n",
      "[2424, 1010]\n",
      "[3838, 1616]\n"
     ]
    }
   ],
   "source": [
    "# 输出结果\n",
    "for row in C:\n",
    "    print(row)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T10:45:06.062058Z",
     "end_time": "2024-07-03T10:45:06.072846Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
